package com.woniuxy.controller;

import com.woniuxy.domain.Product;
import com.woniuxy.service.IProductService;
import com.woniuxy.util.Constants;
import com.woniuxy.util.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author gaopeng
 * @create 2020/04/2020/4/8 10:45:25
 */
@RestController
public class ProductController {
    @Autowired
    private IProductService service;

    @GetMapping("/products/{pid}")
    public ResultVO find(@PathVariable Integer pid) {
        System.out.println("ProductController.find");
        ResultVO resultVO = null;
        try {
            Product product = service.findByPid(pid);
            resultVO = new ResultVO(Constants.OPER_SUCCESS, "test ok", product);
        } catch (Exception e) {
            resultVO = new ResultVO(Constants.OPER_FAILURE, "查询不到该商品");
        }
        return resultVO;
    }

    @GetMapping("/products/deductStock/{pid}/{number}")
    public ResultVO deductStock(@PathVariable Integer pid, @PathVariable Integer number) {
        try {
            service.deductStock(pid, number);
            return new ResultVO(Constants.OPER_SUCCESS, "扣减库存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(Constants.OPER_SUCCESS, "扣减库存失败");

        }
    }

    @GetMapping("/products/testloadbalance")
    public ResultVO testLoadBalance(HttpServletRequest request) {
        return new ResultVO(Constants.OPER_SUCCESS, "处理本次请求的product-service实例端口：" + request.getServerPort());
    }
}
